// 集中管理购物车数据
import {
  defineStore
} from "pinia";
import { reactive } from "vue";

export const useCartStore = defineStore("cart", () => {
  const cartInfo = reactive({
    cartTotalPrice: 0,
    cartTotalNum: 0,
    selectAll: false,
    cartList: []
  })

  const setCartInfo = (data) => {
    cartInfo.cartTotalPrice = data.cartTotalPrice
    cartInfo.cartTotalNum = data.cartTotalQuantity
    cartInfo.selectAll = data.selectAll
    cartInfo.cartList = data.cartProductList
  }

  const addCart = (item) => {
    const index = cartInfo.cartList.findIndex(val => val.id === item.id)
    if (index > -1) {
      cartInfo.cartList[index].quantity++
    } else {
      cartInfo.cartList.push(item)
    }
  }

  const clearCart = () => {
    cartInfo.cartTotalPrice = 0
    cartInfo.cartTotalNum = 0
    cartInfo.selectAll = false
    cartInfo.cartList = []
  }


  return { cartInfo,setCartInfo,addCart,clearCart }
}, {
  persist: true
})